# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2020/2/11 18:19
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : app.py
# @Software   : PyCharm
# -----------------------------------------

import os
import sys

from utils.log import log

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import ipaddress
from utils.dir_files import DirFile
from utils.parase import ParseConf
from concurrent.futures import ProcessPoolExecutor, as_completed  # ,ThreadPoolExecutor
from utils.base import Monitor
from utils.ding import Ding
from utils.feishu import FeiShu
from config.settings import FILE_CONFIG_FILTER, MAX_WORKER


class App:
    def __init__(self):
        pass

    def start(self):
        """
        1. 获取file
        2. 获取file_info
        3. check and send dingding
        :return:
        """
        dir_path, files = self.get_dir_and_files()
        files_info = self.get_files_info(dir_path, files)
        self.check_files_info(files_info)

    def get_dir_and_files(self):
        op_files = DirFile()
        dir_path = op_files.get_dir()
        files = op_files.get('port')
        return dir_path, files

    def get_files_info(self, dir_path, files):
        files_info = {}
        for file in files:
            path = os.path.join(dir_path, file)
            parse = ParseConf(path)
            files_info[file] = parse.get_sections_info()

        return files_info

    def check_files_info(self, files_info):
        if not files_info:
            return None

        tasks = []
        with ProcessPoolExecutor(max_workers=MAX_WORKER) as executor:
            for file, infos in files_info.items():
                for section, options in infos.items():
                    if "default" == section:
                        continue

                    try:
                        ip = section.split('-')[-1]
                        # 解析的非ip地址
                        if not ipaddress.ip_address(ip):
                            continue
                        task=executor.submit(self.check_and_send_msg, section, ip, options)
                        tasks.append(task)
                    except Exception as e:
                        continue
            # 阻塞
            for task in as_completed(tasks):
                try:
                    task.result()
                except Exception as e:
                    print(e)

    def check_and_send_msg(self, section, ip, options):
        if "dingtoken" not in options.keys():
            token = options["feishutoken"]
            ding = FeiShu(token)
        else:
            token = options["dingtoken"]
            ding = Ding(token)

        monitor = Monitor()
        for app, port in options.items():
            if app in FILE_CONFIG_FILTER:
                continue
            try:
                port = int(port)
                if port > 65335 or port < 1:
                    ding.send_text(section, f"{app}: port={port} is valiad!")
                    log.error(f"{app}: port={port} is valiad!")
                    continue

                status_info = monitor.port(ip, port)
                if not status_info["status"]:
                    ding.send_text(section, f"{app}={port} check failed, please check it")
                else:
                    # strs=f"{app}={port} is ok!"
                    # ding.send_text(section,strs)
                    pass
            except Exception as e:
                ding.send_text(section, f"{app}={port} is valiad!")


if __name__ == "__main__":
    app = App()
    app.start()
